package exrefelect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 构造方法类的使用
 * @author: knowno
 * @create: 2025-09-17 14:26
 * @Version 1.0
 **/
public class TestConstructor {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException {

        //得到一个Person类的Class对象
        Class cls = Person.class;

        //获取构造方法
        //1 获取构造方法 ->getConstructors ->只能获取public的构造方法
        System.out.println("************getConstructors**********");
        Constructor[] constructors = cls.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor+" "+constructor.getModifiers());
            //调用带参数的构造方法 ->调用构造,传递参数,返回对象 =>没有new
            Object o = constructor.newInstance("knowno");
            System.out.println(o);

        }


        System.out.println("************getDeclaredConstructors**********");

        //2 获取所有的构造方法 ->getDeclaredConstructors->可以获取所有的构造方法
        Constructor[] declaredConstructors = cls.getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor+" "+declaredConstructor.getModifiers());
            //调用构造方法
            if (declaredConstructor.getModifiers()==2) {
                //调用private的构造方法(作弊)
                declaredConstructor.setAccessible(true);
                Object o = declaredConstructor.newInstance();
                System.out.println(o);
            }
        }

        
    }
}
